package netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * description:
 * author:zt
 * date:2021-09-21
 */
//加上HttpObject表示客户端和服务器通信的数据类型 被封装为HttpObject
    //SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter的子类
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    //该方法 读取客户端数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        //判断msg是不是httpRequest请求
        if(msg instanceof HttpRequest){
            System.out.println(ctx.pipeline().hashCode() + "----" + this.hashCode());
            System.out.println("msg类型为：" + msg.getClass());
            System.out.println("客户端地址为：" + ctx.channel().remoteAddress());

            HttpRequest httpRequest = (HttpRequest) msg;
            //获取uri，过滤指定资源
            URI uri = new URI(httpRequest.uri());
            if ("/favicon.ico".equals(uri.getPath())){
                System.out.println("浏览器请求了favicon.ico,不做响应");
                return;
            }

            //回复信息给浏览器 [http协议]
            ByteBuf buffer = Unpooled.copiedBuffer("hello I AM SERVER!你好", CharsetUtil.UTF_8);
            //构造一个http响应，即httpResponse
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer);

            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=UTF-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,buffer.readableBytes());

            //将构建好的 response返回
            ctx.writeAndFlush(response);

        }
    }
}
